<?php

/**
 * video actions.
 *
 * @package    preuvideo
 * @subpackage video
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class videoActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
    public $yt;

    public function executeIndex(sfWebRequest $request){

        if(isset($_SESSION['state']) && isset($_SESSION['access_token'])){
            $this->fb_id = $_SESSION["fb_id"];
            $this->conectado = true;
            $yt = self::getYoutubeInstance();

            // create a new VideoEntry object
            $myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();

            //print_r($myVideoEntry );

            $myVideoEntry->setVideoTitle('My Test Movie');
            $myVideoEntry->setVideoDescription('My Test Movie');
            // The category must be a valid YouTube category!
            $myVideoEntry->setVideoCategory('Autos');

            // Set keywords. Please note that this must be a comma-separated string
            // and that individual keywords cannot contain whitespace
            $myVideoEntry->SetVideoTags('cars, funny');

            $tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';
            $tokenArray = $yt->getFormUploadToken($myVideoEntry, $tokenHandlerUrl);

            //$tokenArray['url']=str_replace("uploads","uploads2",$tokenArray['url']);
            //print_r($tokenArray);
            $this->tokenValue = $tokenArray['token'];
            $this->postUrl = $tokenArray['url'];
        }
        else{
            $this->conectado = false;
        }

    }
    public function executePrueba(sfWebRequest $request){
        $video = Doctrine_Core::getTable('video')->findOneById(1);
        print_r($video);
        exit;
    }

    public function executeSaveUpload(sfWebRequest $request){
        $fb_id = $request->getParameter("fb_id");
        $tema_id = $request->getParameter("tema_id_2");
        $youtube_id = $request->getParameter("youtube_id");
        $youtube_url = $request->getParameter("youtube_url");
        $select_get_or_upload = $request->getParameter("select_get_or_upload");
        
        //print_r($_POST);


        if($youtube_url){
            if (preg_match('![?&]{1}v=([^&]+)!', $youtube_url . '&', $m))
                $youtube_id = $m[1];
            else{
                exit;
            }
        }
        else{

        }
        
        //echo '<div>$fb_id: '.$fb_id.'</div>';
        //echo '<div>$tema_id: '.$tema_id.'</div>';
        //echo '<div>$youtube_id: '.$youtube_id.'</div>';

        $video= new Video();
        //print_r($video);
        //exit;
        
        
        $video->setTemaId($tema_id);
        $video->setFacebookId($fb_id);
        $video->setYoutubeId($youtube_id);
        $video->save();
        $this->redirect('tema/show?id='.$tema_id.'&video_nuevo='.$youtube_id);

    }
    public function executeUpload(sfWebRequest $request){
        $id = $request->getParameter("id");
        $this->id = $id;
        
        $this->setLayout("blank");
    }
    public function executeUploadFrame(sfWebRequest $request){
        $this->setLayout("blank");
        $postUrl = $request->getParameter("postUrl");
        $tokenValue = $request->getParameter("tokenValue");

        $this->postUrl = $postUrl;
        $this->tokenValue = $tokenValue;
                        
    }

    public function executeRetrievingVideoEntry(sfWebRequest $request){
        $yt = self::getYoutubeInstance();
        $url = $request->getParameter("url");

        //echo '<div>url: '.$url.'</div>';
        if (preg_match('![?&]{1}v=([^&]+)!', $url . '&', $m))
            $id = $m[1];
        else{
            $id=null;
        }


        
        

        //echo '<div>Id: '.$id.'</div>';

        try{
            $videoEntry = $yt->getVideoEntry($id);
        }catch (Exception $e) {
            //echo 'Caught exception: ',  $e->getMessage(), "\n";
            $videoEntry = null;
        }
        
        //print_r($videoEntry);

        if($videoEntry!=null){
            $resultado = "Video Ok";
        }
        else{
            $resultado = "No existe el video";
        }

        return $this->renderPartial('retrievingVideoEntry', array("resultado" => $resultado));
    }
    function showVideos(){
        $yt=Youtube::getInstance();
        $location = Zend_Gdata_YouTube::VIDEO_URI;
        //$yt->setMajorProtocolVersion(2);
        //$videoFeed = $yt->getVideoFeed($location);
        //$this->printVideoFeed($videoFeed);
        $videoEntry = $yt->getVideoEntry('the0KZLEacs');
        $this->printVideoEntry($videoEntry);
    }

    function printVideoFeed($videoFeed){
        $count = 1;
        foreach ($videoFeed as $videoEntry) {
            echo "Entry # " . $count . "\n";
            $this->printVideoEntry($videoEntry);
            echo "\n";
            $count++;
        }
    }
    public function printVideoEntry($videoEntry) {
      // the videoEntry object contains many helper functions
      // that access the underlying mediaGroup object
      echo 'Video: ' . $videoEntry->getVideoTitle() . "\n";
      echo 'Video ID: ' . $videoEntry->getVideoId() . "\n";
      echo 'Updated: ' . $videoEntry->getUpdated() . "\n";
      echo 'Description: ' . $videoEntry->getVideoDescription() . "\n";
      echo 'Category: ' . $videoEntry->getVideoCategory() . "\n";
      echo 'Tags: ' . implode(", ", $videoEntry->getVideoTags()) . "\n";
      echo 'Watch page: ' . $videoEntry->getVideoWatchPageUrl() . "\n";
      echo 'Flash Player Url: ' . $videoEntry->getFlashPlayerUrl() . "\n";
      echo 'Duration: ' . $videoEntry->getVideoDuration() . "\n";
      echo 'View count: ' . $videoEntry->getVideoViewCount() . "\n";
      echo 'Rating: ' . $videoEntry->getVideoRatingInfo() . "\n";
      echo 'Geo Location: ' . $videoEntry->getVideoGeoLocation() . "\n";
      echo 'Recorded on: ' . $videoEntry->getVideoRecorded() . "\n";

      // see the paragraph above this function for more information on the
      // 'mediaGroup' object. in the following code, we use the mediaGroup
      // object directly to retrieve its 'Mobile RSTP link' child
      foreach ($videoEntry->mediaGroup->content as $content) {
        if ($content->type === "video/3gpp") {
          echo 'Mobile RTSP link: ' . $content->url . "\n";
        }
      }

      echo "Thumbnails:\n";
      $videoThumbnails = $videoEntry->getVideoThumbnails();

      foreach($videoThumbnails as $videoThumbnail) {
        echo $videoThumbnail['time'] . ' - <img src="' . $videoThumbnail['url'].'">';
        echo ' height=' . $videoThumbnail['height'];
        echo ' width=' . $videoThumbnail['width'] . "\n";
      }
    }

    public static function getYoutubeInstance(){
        require_once 'Zend/Loader.php'; // the Zend dir must be in your include_path
        Zend_Loader::loadClass('Zend_Gdata_YouTube');
        Zend_Loader::loadClass('Zend_Gdata_ClientLogin');

        //$yt = new Zend_Gdata_YouTube();
       
        //echo '<div>Cliente: '.sfConfig::get('app_youtube_user').'</div>';
        ## LOGIN
        //session_start();
        $authenticationURL= 'https://www.google.com/accounts/ClientLogin';
        $httpClient = Zend_Gdata_ClientLogin::getHttpClient(
                      $username = sfConfig::get('app_youtube_user'),
                      $password = sfConfig::get('app_youtube_password'),
                      $service = 'youtube',
                      $client = null,
                      $source = 'Preuvideo_dev', // a short string identifying your application
                      $loginToken = null,
                      $loginCaptcha = null,
                      $authenticationURL);
        ## END LOGIN


        $developerKey = 'AI39si41ZzvSJyAS6rXywdVVTSnmkwS5WGPvTvE0gjmfrDpxmtrwgUUyvmK-FPPjpcWv0d8NiUZ37h-TFazKwZpghj7gE3hXrg';
        $applicationId = 'Video uploader v1';
        $clientId = 'My video upload client - v1';

        $yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);
        return $yt;
    }
}
